<!-- 文件所有权归北京优博泰克 -->
<template>
    <div class="loginWrap">
        <div class="loginBox" v-loading="loading" element-loading-text="登录中"
            element-loading-background="rgba(255, 255, 255, 1)">
            <div class="leftBox">
                <p>登录</p>
                <img @click="showsettingbox" src="@/assets/img/logo.png">
            </div>
            <div class="rightBox">
                <el-form :model="loginForm" status-icon ref="ruleFormInstance" label-width="1px" class="demo-ruleForm"
                    label-position="left" :show-message="false">
                    <p class="oyjory">用户名</p>
                    <el-form-item label="" prop="username">
                        <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
                    </el-form-item>
                    <p class="oyjory">密码</p>
                    <el-form-item label="" prop="password">
                        <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password />
                    </el-form-item>
                    <el-form-item>
                        <div class="loginbtn" @click="postUpdateIsLogin()">
                            登录
                        </div>
                    </el-form-item>
                    <div class="mlkre">
                        <el-checkbox v-model="selectRemember">记住密码</el-checkbox>
                        <p style="color: #409eff;font-size:14px; cursor: pointer;" @click="otherLoginHandle">
                            IAM登录
                        </p>
                    </div>
                </el-form>
            </div>
        </div>
        <p class="companyCopyright">
            本系统兼容Chrome,FireFox浏览器，为了浏览达到最佳效果，建议使用以上指定浏览器。
        </p>
        <!-- 设置弹窗 -->
        <setting-box v-if="modalStatus == '后台地址设置弹窗'" ref="mysettingbox"></setting-box>
    </div>
</template>
<script setup>
import { reactive, ref, onMounted, toRefs, computed } from 'vue'
import api from '@/api'
import { useCach } from '@/store/cach'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'

onMounted(() => {
    openFunction()
})

const router = useRouter()
const route = useRoute()

let emits = defineEmits(['showTestBox'])

let ruleFormInstance = ref(null)

let cachInfo = useCach()

let state = reactive({
    selectRemember: false,
    loading: false,
    loginForm: {
        username: "",
        password: "",
        keeplogin: false
    },
    rules: {
        username: [{
            required: true,
            trigger: "blur",
            message: "请输入用户名"
        }],
        password: [{
            required: true,
            trigger: "blur",
            message: "请输入密码"
        }]
    }
})
let { selectRemember, loading, loginForm, rules } = toRefs(state)

let modalStatus = computed(() => cachInfo.modalStatus)

let openFunction = () => {
    localStorage.setItem("Token", "")
    //IMA登录
    analysisHandle()

    //判断是否记住用户名
    if (localStorage.getItem("selectRemember")) {
        state.selectRemember = true
        state.loginForm.username = localStorage.getItem("username")
        state.loginForm.password = localStorage.getItem("password")
        return
    }
    state.loginForm.username = ""
    state.loginForm.password = ""
}

//登录函数
let postUpdateIsLogin = () => {
    ruleFormInstance.value.validate(async valid => {
        if (!valid) return
        state.loading = true
        let params = {}
        params.username = state.loginForm.username
        params.password = state.loginForm.password
        let res = await api.changeaxiosdata('login', 'post', params)
        if (res) {
            state.loading = false
            if (res.status == "success") {
                //未冻结用户
                cachInfo.setUserMsg(res.msg.usermsg)
                localStorage.setItem("Token", res.msg.token)
                setselectRemember()
                getcurrentUserMsg(res.msg.usermsg.id)
                return
            }
            //冻结的用户 需要先激活
            if (res.account_status == "freeze") {
                securityIntended()
                ElMessage({
                    message: '密码错误次数过多,请先完成效验后再试!!',
                    type: 'warning'
                })
                return
            }

            ElMessage.error(res.msg)
        }
    })
}

let getcurrentUserMsg = async (id) => {
    state.loading = true
    let params = {}
    params.id = id
    let res = await api.getaxiosdata('users', params)
    if (res) {
        state.loading = false
        localStorage.setItem("UserMsg", JSON.stringify(res.results[0]))
        await getdepartment()
        await getstationmsgNum()
        router.push({
            path: "/home"
        })
        ElMessage({
            message: "登录成功",
            type: "success"
        })
    }
}

/* 获取科室 */
let getdepartment = async () => {
    state.loading = true
    let results = await api.getaxiosdata("department")
    if (results) {
        state.loading = false
        localStorage.setItem("department", JSON.stringify(results))
    }
}

//获取站内信未读数量
let getstationmsgNum = async () => {
    let params = {}
    params.user_id = JSON.parse(localStorage.getItem("UserMsg")).id
    params.ifread = false
    let res = await api.getaxiosdata('PutMsg', params)
    if (res) {
        cachInfo.unredmsgNum(res.count)
    }
}

//显示配置弹窗
let showsettingbox = () => {
    cachInfo.changeShowModal(true)
    cachInfo.changeModalStatus('后台地址设置弹窗')
}

//安全效验
let securityIntended = () => {
    emits('showTestBox')
}

let setselectRemember = () => {
    if (state.selectRemember) {
        localStorage.setItem("username", state.loginForm.username)
        localStorage.setItem("password", state.loginForm.password)
        localStorage.setItem("selectRemember", true)
        return
    }
    localStorage.setItem("selectRemember", false)
}

//其他登录方式
let otherLoginHandle = () => {
    window.location.href = `https://iam.dfcv.com.cn/idp/oauth2/authorize?redirect_uri=${encodeURIComponent('https://dtms.dfcv.com.cn/#/')}&state=123&client_id=DTMS&response_type=code`
}

//解析iam请求回调code
let analysisHandle = async () => {
    let code = route.query.code || ''
    if (!code) return
    state.loading = true
    let res = await api.getaxiosdata('cas_iam_index', { code })
    if (res) {
        state.loading = false
        //冻结的用户 需要先激活
        if (res.account_status == "freeze") {
            securityIntended()
            ElMessage({
                message: '密码错误次数过多,请先完成效验后再试!!',
                type: 'warning'
            })
            return
        }

        if (res.status == "success") {
            //未冻结用户
            cachInfo.setUserMsg(res.msg.usermsg)
            localStorage.setItem("Token", res.msg.token)
            setselectRemember()
            getcurrentUserMsg(res.msg.usermsg.id)
            return
        }

        ElMessage.error(res.msg)
    }
    state.loading = false
}

</script>
<style scoped lang="scss">
.loginBox {
    z-index: 1;
    /* width: 440px;
    height: 340px; */
    background: rgba(255, 255, 255, 1);
    box-shadow: 2px 4px 8px 0px rgba(0, 0, 0, 0.5);
    padding: 30px 20px;
}

.leftBox {
    display: flex;
    justify-content: space-between;
    color: #1f2d3d;
    font-size: 24px;
    font-weight: 500;
    line-height: 33px;
}

.rightBox {
    margin-top: 20px;

    :deep(.el-input) {
        width: 100%;
        height: 44px;
    }
}

.oyjory {
    color: #8492a6;
    font-size: 18px;
    margin-bottom: 10px;
}

.loginbtn {
    width: 440px;
    height: 44px;
    background: rgba(1, 101, 180, 1);
    border-radius: 4px;
    text-align: center;
    color: #ffffff;
    font-size: 18px;
    line-height: 44px;
    margin-top: 20px;
    margin-bottom: 10px;
}

.el-form-item {
    margin-bottom: 0;
}

.mlkre {
    display: flex;
    justify-content: space-between;
}

.companyCopyright {
    bottom: 300px;
    color: #ffffff;
    width: 400px;
    font-size: 14px;
    margin-top: 20px;
    /*text-align: center;*/
    margin-left: 40px;
}
</style>
